<?php
namespace app\store\controller\shouhuo;

use app\store\model\Device;
use think\Request;

class Xykw
{
    //星云开物通知

    protected $domain = 'https://testopenapi.ksepton.com/open-service'; //星云开物域名
    protected $app_key = 'EP2024241620268';
    protected $app_secret = 'e43f8120a7u94cb4c8515294233a2b12';

    public function obj(){
        return new Device();
    }

    //通知接口
    public function notice(Request $request)
    {
        $pas = $request->param();
        $res = $this->obj()->xykwNotice($pas);
        return $this->toJson(0, '', $res);
    }

    /**
     * 接口签名
     * @param array $params 请求参数
     */
    public function apiSign($params)
    {
        ksort($params);
        $param = json_encode($params);
        //$rand = strval(rand(1000, 9999));
        $rand = $this->randStr(rand(10, 20));
        $signs = [
            'api_key' => $this->app_key,
            'data' => $param,
            'random_str' => $rand,
            'api_secret' => $this->app_secret,
        ];
//        ksort($signs);
        $str = '';
        foreach ($signs as $k => $v) {
            if ($str) {
                $str .= '&'.$k.'='.$v;
            } else {
                $str = $k.'='.$v;
            }
        }
//        var_dump($str);
        $str = md5($str);
//        var_dump($str);
//        $str = bin2hex($str);
//        var_dump($str);
        return [
            'random_str' => $rand,
            'data' => $params,
            'api_key' => $this->app_key,
            'sign' => $str,
        ];
    }

    //设备列表
    public function deviceList()
    {
        $httpUrl = $this->domain.'/equipment/list';
        $httpData = [
            'page' => "1",
            'size' => "10",
        ];
//        echo '<pre>';
//        var_dump($httpUrl);
        $httpData = $this->apiSign($httpData);
        $httpData = json_encode($httpData);
//        var_dump($httpData);
        $res = $this->toCurl($httpUrl, 1, $httpData);
//        var_dump($res);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
//        var_dump($res['data']);
        $res = $res['data'];
        if ($res['code'] != 200) {
            return $this->toJson(-2, $res['message']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    //设备详情
    public function deviceOne()
    {
        $httpUrl = $this->domain.'/equipment/info';
        $httpData = [
            'equipment_id' => '91238248',
        ];
        $httpData = $this->apiSign($httpData);
        $httpData = json_encode($httpData);
        var_dump($httpUrl, $httpData);
        $res = $this->toCurl($httpUrl, 1, $httpData);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res);
        }
        ddd($res['data']);
    }

    //设备绑定
    public function bind(Request $request)
    {
        $imei = $request->param('imei', ''); //设备编号
        $door01 = $request->param('door01', ''); //左门编号
        $door02 = $request->param('door02', ''); //右门编号
        if (!$imei) {
            return $this->toJson(-2, '设备编号必须的');
        }
        if (!$door01) {
            return $this->toJson(-2, '左门编号必须的');
        }
        $httpUrl = $this->domain.'/equipment/bind';
        $httpData = [
            'imei' => $imei, //设备编号
            'left_equipment_id' => $door01, //左门编号
            'right_equipment_id' => $door02, //右门编号
        ];
        $httpData = $this->apiSign($httpData);
        $httpData = $this->apiSign($httpData);
        $httpData = json_encode($httpData, JSON_UNESCAPED_UNICODE);
        ddd($httpData);
        $res = $this->toCurl($httpUrl, 1, $httpData);
        if ($res['coe'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //设备解绑
    public function unbind(Request $request)
    {
        $imei = $request->param('imei', ''); //设备编号
        $doorno = $request->param('doorno', ''); //门编号
        $httpUrl = $this->domain.'/equipment/unbind/imei';
        $httpData = [
            'imei' => $imei, //套件编号
            'third_equipment_id' => $doorno, //设备编号
        ];
        $httpData = $this->apiSign($httpData);
        $httpData = json_encode($httpData, JSON_UNESCAPED_UNICODE);
        $res = $this->toCurl($httpUrl, 1, $httpData);
        if ($res['coe'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //设备开门
    public function doorOpen(Request $request)
    {
        $doorno = $request->param('doorno', ''); //门编号
        $httpUrl = $this->domain.'/equipment/opendoor';
        $httpData = [
            'equipment_id' => $doorno, //设备编号
            'type' => 'consume', //consume 消费； manage 管理
//            'order_sn' => '', //订单号，可空，有订单号
//            'is_algorithm' => 1, //订单是否自己去经过算法 默认为1，仅对消费
        ];
        $httpData = json_encode($httpData, JSON_UNESCAPED_UNICODE);
        $res = $this->toCurl($httpUrl, 1, $httpData);
        if ($res['coe'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //返回结果
    public function toJson($code = 200, $msg = 'success', $data = [])
    {
        return json_encode([
            'code' => $code ? $code : 200,
            'message' => $msg ? $msg : 'success',
            'data' => $data,
        ], true);
    }

    /**
     * 生成随机字符串，默认数字字母混合
     * @param int $numeric 0纯数字
     */
    public function randStr($length = 6, $numeric = 1) {
        if(!$numeric) {
            //纯数字
            $str = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
        } else {
            //数字、字母组合
            $str = '';
            $chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
            $max = strlen($chars) - 1;
            for($i = 0; $i < $length; $i++) {
                $str .= $chars[mt_rand(0, $max)];
            }
        }
        return $str;
    }

    /**
     * 构建CURL请求
     * @param string $url 请求地址
     * @param int $method 请求方式：0get，1post
     * @param string $sring 请求数据
     */
    public function toCurl($url, $method = 0, $string = '')
    {
        $headers = array(
            //'Accept: application/json',
            'Content-Type: application/json',
            //'Custom-Header: YourValue' // 自定义头部信息
        );
//        var_dump($headers);
        $curl = curl_init(); //初始化
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_TIMEOUT, 5);
        if ($method) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $string);
        }
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        $output = curl_exec($curl);
        curl_close($curl);
        if (!$output) {
            return array('code'=> -1, 'msg'=>'请求失败');
        }
        $items = json_decode($output,true);
        return array('code' => 0, 'msg' => 'success', 'data' => $items);
    }
}